import React, { useState, useEffect } from 'react';
import { Modal, Button, Input, message, Radio, Spin } from 'antd';
import { useRef } from 'react';

const Payment = ({ visible, onClose, totalPrice, paymentMethod, onPaymentSuccess }) => {
  const defaultPaymentType = paymentMethod === 'wechat'? 'scan' : paymentMethod === 'alipay'? 'scan' : 'bank';
  const [loading, setLoading] = useState(false);
  const [paymentType, setPaymentType] = useState(defaultPaymentType);
  const [barcode, setBarcode] = useState('');
  const paycodeInputRef = useRef(null);

  console.log(paymentMethod, defaultPaymentType, paymentType);

  useEffect(() => {
    if (paycodeInputRef.current) {
      paycodeInputRef.current.focus();
    }
  }, [visible, paycodeInputRef.current])

  const handlePaymentSuccess = () => {
    // 语音播报
    const utterance = new SpeechSynthesisUtterance('收款成功');
    speechSynthesis.speak(utterance);
    
    message.success('支付成功', 3);
    
    setTimeout(() => {
        setLoading(false);
        onClose();    
    }, 500);
    
    onPaymentSuccess(); // 调用清空购物车的回调
  };

  const onScanPaycode = (event) => {
    const paycode = event.target.value;
    setBarcode(paycode);
    if (paycode.length > 10) {
        setBarcode('');
        handleConfirmPayment();
    }
  }

  const handleConfirmPayment = () => {
    if (paymentType === 'scan' && !barcode) {
      message.warning('请扫描支付条码');
      return;
    }

    setLoading(true);
    
    if (paymentType === 'scan') {
      // 扫码支付需要2秒处理时间
      setTimeout(handlePaymentSuccess, 2000 + Math.floor(Math.random() * 1000));
    } else {
      // 现金/银行卡支付立即完成
      handlePaymentSuccess();
    }
  };

  return (
    <Modal
      title="支付"
      open={visible}
      onCancel={onClose}
      footer={null}
      centered
      width={600}
      bodyStyle={{ height: 300 }}
    >
      <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
        <div style={{ marginBottom: 24 }}>
          <div style={{ fontSize: 18, marginBottom: 8 }}>
            支付金额: <span style={{ fontWeight: 'bold', color: '#ff0f23' }}>¥{totalPrice.toFixed(2)}</span>
          </div>
          <div style={{ fontSize: 16 }}>
            当前支付方式: <b>{paymentMethod === 'wechat' ? '微信支付' : paymentMethod === 'alipay' ? '支付宝支付' : '银行卡支付'}</b>
          </div>
        </div>

        <Radio.Group
          value={paymentType}
          onChange={(e) => setPaymentType(e.target.value)}
          style={{ marginBottom: 24 }}
        >
          <Radio.Button value="scan">扫码支付</Radio.Button>
          <Radio.Button value="bank">银行卡支付</Radio.Button>
          <Radio.Button value="cash">现金支付</Radio.Button>
        </Radio.Group>

        <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          {loading ? (
            <Spin size="large" tip="支付处理中..." />
          ) : paymentType === 'scan' ? (
            <Input
              placeholder="请扫描支付条码"
              value={barcode}
              onKeyDown={event => event.stopPropagation()}
              onChange={(e) => onScanPaycode(e)}
              size="large"
              style={{ height: 100, fontSize: 30 }}
              ref={paycodeInputRef}
            />
          ) : (
            <div style={{ fontSize: 18, color: '#666' }}>
              请您通过{paymentType === 'cash' ? '现金' : '银行卡'}支付，支付完成后请点击下方【确认已收款】按钮
            </div>
          )}
        </div>

        <div style={{ textAlign: 'center', marginTop: 24 }}>
          {paymentType !== 'scan' && (
            <Button 
              type="primary" 
              size="large" 
              onClick={handleConfirmPayment}
              style={{ width: 200 }}
            >
              确认已收款
            </Button>
          )}
        </div>
      </div>
    </Modal>
  );
};

export default Payment;
